package com.bdy.lm.browser.controller;

import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bdy.lm.browser.service.UserService;
import com.bdy.lm.common.model.User;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	public static Logger logger = Logger.getLogger(UserController.class);
	
	@RequestMapping(value = "/register")
	public String register() {
		logger.info("hahalog");
		return "register";
	}
	
	@RequestMapping(value = "/registerVerify", method = RequestMethod.POST)
	public String registerVerify(@ModelAttribute User user, Model model) {
		if (user.getName().equals("")) {
			model.addAttribute("msg", "用户名不为空");
			return "register";
		} else if (user.getPassword().equals("")) {
			model.addAttribute("msg", "密码不为空");
			return "register";
		}
		if (userService.register(user)) {
			model.addAttribute("msg", "注册成功");
			return "success";
		} else {
			model.addAttribute("msg", "注册失败");
			return "register";
		}
	}
	
	@RequestMapping(value = "/login")
	public String login() {
		return "login";
	}
	
	@RequestMapping(value = "/loginVerify", method = RequestMethod.POST)
	public String loginVerify(@ModelAttribute User user, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			System.out.println("Code:" + fieldError.getCode() + ", field:" + fieldError.getField());
			model.addAttribute("msg", "登录失败，错误码：" + fieldError.getCode());
			return "login";
		}
		for(Entry<String, Object> entry : model.asMap().entrySet()) {
			System.out.println("键:" + entry.getKey() + "   值:" + entry.getValue());
		}
		System.out.println("用户信息：" + user);
		if (userService.login(user) != null) {
			model.addAttribute("msg", "登录成功");
			return "success";
		} else {
			model.addAttribute("msg", "登录失败");
			return "login";
		}
	}

}
